﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;

namespace haber.classes
{
    public class TimerStarter
    {
        private static Timer threadingTimer;
      
         public static void StartTimer()
         {
            if (null == threadingTimer)
             {
                threadingTimer = new Timer(new TimerCallback(CheckData),
                                           HttpContext.Current, 0, 60000);
            }
       }
        private static void CheckData(object sender)
        {
            using (dcHaberDataContext dc = new dcHaberDataContext())
            {
                var delete = from p in dc.MesajZamans
                            where p.KalanGondermeAdedi == 0
                            select p;
                dc.MesajZamans.DeleteAllOnSubmit(delete);
                dc.SubmitChanges();
                var posts = from p in dc.MesajZamans
                            where p.SonrakiGondermeZamani >= DateTime.Now.AddMinutes(-1) && p.SonrakiGondermeZamani <= DateTime.Now.AddMinutes(10)
                            select p;
                if (posts.Count() > 0)
                {
                    foreach (var po in posts)
                    {
                        //Gonderrr
                        statics.facebookGonder(po.HaberID);
                        statics.twitterGonder(po.HaberID);
                        //
                        po.KalanGondermeAdedi = po.KalanGondermeAdedi - 1;
                        po.SonrakiGondermeZamani = DateTime.Now.AddDays(1).AddMinutes(1);
                    }
                }
                dc.SubmitChanges();
                posts = null;
                delete = null;
                System.GC.Collect();

            }
       }
    }
}